package com.orangelife.mobile.parkingcard.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.JSONHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.view.ConfirmDialog;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.constants.ParkingCardURL;
import com.orangelife.mobile.parkingcard.adapter.CarNumListAdapter;
import com.orangelife.mobile.parkingcard.bean.ParkingInfomation;
import com.orangelife.mobile.parkingcard.biz.ParkingCardHttpBiz;
import com.orangelife.mobile.util.StringUtil;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by yyx
 * on 2015/11/17.
 */
public class ManageCarActivity extends OrangeLifeBaseActivity implements View.OnClickListener,AdapterView.OnItemLongClickListener{

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.lvManageCar)
    ListView lvManageCar;
    @Bind(R.id.etCarNum)
    EditText etCarNum;
    @Bind(R.id.tvAddPlate)
    TextView tvAddPlate;
    @Bind(R.id.btnSubmit)
    Button btnSubmit;

    private CarNumListAdapter<Map<String, Object>> adapter = null;

    private Dialog dialog;
    /**
     * 车牌列表请求地址
     */
    private static final String urlPlate = "";

    private List<Map<String, Object>> list;

    private int position;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parking_manage);

        ButterKnife.bind(this);

        initView();
        findView();
    }

    private void initView() {
        tvTitle.setText("管理车辆");
    }

    private void findView() {
        list = ParkingInfomation.getListTotal();
        setAdapter();
        tvAddPlate.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);
        lvManageCar.setOnItemLongClickListener(this);

    }

    /**
     * 进度圈
     */
    private void getDataFromServer() {
        dialog = DialogHelper.getInstance().createLoadingDialog(this, Constant.LOADING);
        dialog.show();
    }

    /**
     *
     */
    private void setAdapter() {
        adapter = new CarNumListAdapter(this, list);
        lvManageCar.setAdapter(adapter);
    }


    /**
     * 请求车牌列表
     */
//    private void submittPlate() {
//        Map<String,Object> mapR = new HashMap<>();
//        mapR.put("plateList",list);
//        Map<String, Object> rootMap = new HashMap<>();
//        rootMap.put("map", mapR);
//        rootMap.put("url",urlEditPlate);
//        rootMap.put("wat", 1);
//        JSONRequest.getInstance().sendRequest(JSONRequest.POST, rootMap, handler, HttpUtil.ACTION_JSON);
//    }
    private void submittPlate() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("plateList", list);

        VolleyHttpUtil.getInstance().postWithCallback(ParkingCardURL.MANAGE_ADD, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                DialogHelper.closeDialog(dialog);
                String errInfo = JSONHelper.jsonToMap(String.valueOf(jsonObject))
                        .get("errInfo").toString();
                if (errInfo.equals("OK")) {
                    DialogHelper.closeDialog(dialog);
                    ToastHelper.getInstance()._toast("保存成功！");
                    finish();
                }
            }
        });
    }

    /**
     * 删除车牌
     */
    private void deletePlate(){
        String num_plate = list.get(position).get("num_plate").toString();
        HashMap<String,String> map = new HashMap<>();
        map.put("num_plate", num_plate);
        ParkingCardHttpBiz.requestDelete(map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                if (errCode == 0) {
                    list.remove(position);
                    adapter.notifyDataSetChanged();
                    adapter.setList(list);
                    ToastHelper.getInstance()._toast("删除成功");
                }else {
                    Map<String,Object> map=JSONHelper.jsonobjToMap(response);
                    String errInfo=String.valueOf(map.get("errInfo"));
                    ToastHelper.getInstance()._toast("错误码:"+errCode+","+errInfo);
                }
            }
        }, ParkingCardURL.MANAGE_DELETE);
    }

    @Override
    public void onClick(View v) {
        String carNum = etCarNum.getText().toString();
        int number = 0;
        switch (v.getId()) {
            case R.id.tvAddPlate:
                if(!StringUtil.isBlank(etCarNum.getText().toString())) {
                    if (StringUtil.isPlate_(etCarNum.getText().toString())) {
                        if(list != null) {
                            for (int i = 0; i < list.size(); i++) {
                                if(list.get(i).get("num_plate").toString().equals(carNum)){
                                    number ++;
                                }
                            }
                            if(number == 0){
                                Map<String, Object> map = new HashMap<>();
                                map.put("num_plate", etCarNum.getText().toString());
                                map.put("id", "");
                                list.add(map);
                            }else{
                                ToastHelper.getInstance()._toast("车牌已存在！");
                            }
                        }
                        adapter.notifyDataSetChanged();
                        adapter.setList(list);
                        etCarNum.setText("");
                    }else{
                        ToastHelper.getInstance()._toast("车牌格式错误");
                    }
                }else{
                    ToastHelper.getInstance()._toast("请输入车牌号");
                }
                break;
            case R.id.btnSubmit:
                if(!StringUtil.isBlank(etCarNum.getText().toString())){
                    if (StringUtil.isPlate_(etCarNum.getText().toString())) {
                        if(list != null) {
                            for (int i = 0; i < list.size(); i++) {
                                if(list.get(i).get("num_plate").toString().equals(carNum)){
                                    number ++;
                                }
                            }
                            if(number == 0){
                                Map<String, Object> map = new HashMap<>();
                                map.put("num_plate", etCarNum.getText().toString());
                                map.put("id", "");
                                list.add(map);
                                getDataFromServer();
                                submittPlate();
                            }else{
                                ToastHelper.getInstance()._toast("车牌已存在！");
                            }
                        }
                    }else{
                        ToastHelper.getInstance()._toast("车牌格式错误");
                    }
                }else {
                    getDataFromServer();
                    submittPlate();
                }
                break;
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        this.position = position;
        isDeleteDialog();
        return true;
    }

    /** 弹出对话框 */
    private void isDeleteDialog() {
        final ConfirmDialog dialog = new ConfirmDialog(ManageCarActivity.this, "温馨提示","是否删除?", "否", "是");
        dialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doLeft() {
                dialog.dismiss();
            }

            @Override
            public void doRight() {
                deletePlate();
                dialog.dismiss();
            }
        });
        dialog.show();
    }
    private void isDeleteDialog1() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ManageCarActivity.this);
        builder.setMessage("是否删除？");
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                deletePlate();
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    /**
     * 处理获得的数据
     */
    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    DialogHelper.closeDialog(dialog);
                    String errInfo = JSONHelper.jsonToMap(msg.obj.toString())
                            .get("errInfo").toString();
                    if (errInfo.equals("OK")) {
                        DialogHelper.closeDialog(dialog);
                        ToastHelper.getInstance()._toast("保存成功！");
                        finish();
                    }
                    break;
                case 500:
                    DialogHelper.closeDialog(dialog);
                    ToastHelper.getInstance()._toast(
                            msg.obj.toString());
                    list.remove(list.size() - 1);
                    etCarNum.setText("");
                    break;
                case 1011:
                    isLogin(dialog);
                    break;

                default:
                    break;
            }
        }

    };
}
